package logic

import (
	"context"
	"errors"
	"novel/models/mysql"

	"novel/novelrpc/internal/svc"
	"novel/novelrpc/novelrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type BookShelfDelLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBookShelfDelLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BookShelfDelLogic {
	return &BookShelfDelLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 书籍下架
func (l *BookShelfDelLogic) BookShelfDel(in *novelrpc.BookShelfDelRequest) (*novelrpc.BookShelfDelResponse, error) {
	// todo: add your logic here and delete this line
	var bookshelf mysql.Bookshelf
	err := bookshelf.FindBookshelf(mysql.DB, in.UserId, in.NovelId)
	if err != nil {
		return nil, err
	}

	begin := mysql.DB.Begin()
	if bookshelf.ID == 0 {
		begin.Rollback()
		return nil, errors.New("书籍不存在,无需下架")

	}
	err = bookshelf.BookSelfDel(begin, in.UserId, in.NovelId)
	if err != nil {
		begin.Rollback()
		return nil, errors.New("下架失败")
	}
	begin.Commit()
	return &novelrpc.BookShelfDelResponse{}, nil
}
